<template>
    <div class="location">
      <top-bar>
        <p slot="title">{{title}}</p>
        <p v-show="flag" slot="right" class="addAddress" @touchstart="gotoAddNewAdr">新建地址</p>
      </top-bar>
      <section class="searchBox">
        <div class="currentLocation">{{currentCity}}</div>
        <div class="inputBox"><input ref="searchText" @keyup="KeyUpSearch" type="text" placeholder="输入您想要搜索的详细地点"/></div>
        <div class="searchBtn" @touchstart="KeyUpSearch">搜索</div>
      </section>
      <scroll class="location-scroll" :data="searchData">
        <div>
          <div class="divider"><img src="../../../static/img/located.png"/>历史收货地址</div>
          <ul class="nearby">
            <li class="nearby-item" v-for="item in historyLocation">
              <p class="name">{{item.city+item.receptionAddress+item.detailAddress}}</p>
              <p class="area">{{item.consignee}}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{item.phone}}</p>
            </li>
          </ul>
          <div class="divider"><img src="../../../static/img/located.png"/>附近地址</div>
          <ul class="nearby" id="nearby" ref="nearBy">
            <li class="nearby-item" v-for="item in searchData" @click="selectLocation(item.pname+item.cityname+item.address+item.name)">
              <p class="name">{{item.name}}</p>
              <p class="area">{{item.pname}}{{item.cityname}}{{item.address}}</p>
            </li>
            <li class="nearby-item flex" v-if="searchData">
              <div class="left">
                <p class="left-name">无法获取定位，请刷新重试</p>
                <p class="left-area">这里是...</p>
              </div>
              <div class="right">
                <img class="right-img" src="../../../static/img/reLocated.png"/>
                <p class="right-content">重新定位</p>
              </div>
            </li>
          </ul>
        </div>
      </scroll>
      <transition name="addNewLocation">
        <router-view></router-view>
      </transition>
      <div id="temp" style="display:none"></div>
    </div>
</template>

<script>
    import TopBar from "../top-bar/top-bar";
    import Scroll from "../scroll/scroll";
    import {mapMutations, mapGetters} from 'vuex'
    import {setHeightKeyWord} from "../../common/js/dom";

    export default {
      components: {
        Scroll,
        TopBar},
      name: "location",
      data () {
        return {
          searchData: [],
          currentCity: '广州市',
          title: '选择收货地址',
          flag: true
        }
      },
      mounted () {
        this._initLocation()
        this.getCurrentLocation('华南农业大学')
      },
      methods: {
        _initLocation () {
          let _this = this
          AMap.service(["AMap.Geolocation"], function () {
            let geolocation = new AMap.Geolocation({
              enableHighAccuracy: true,//是否使用高精度定位，默认:true
              timeout: 10000,          //超过10秒后停止定位，默认：无穷大
              maximumAge: 0,           //定位结果缓存0毫秒，默认：0
              convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
              showButton: true,        //显示定位按钮，默认：true
              buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
              buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
              showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
              showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
              panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
              zoomToAccuracy:true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            });
            //getCurrentPosition方法需要使用https协议，所以我只能使用定位到城市的getCityInfo方法了
            geolocation.getCityInfo((status, result) => {
              if (status == 'complete') {
                // console.log(result)
                _this.currentCity = result.city // 获取到定位的城市
              } else if (status == 'error') {
                if (result.info == 'FAILED') {
                  alert('获取您当前位置失败！')
                }
              }
            });
          })
        },
        KeyUpSearch () {
          var txt = this.$refs.searchText.value
          this.getCurrentLocation(txt)
        },
        getCurrentLocation(txt) {
          var _this = this
          AMap.service(["AMap.PlaceSearch"], function() {
            var placeSearch = new AMap.PlaceSearch({
              //构造地点查询类
              pageSize: 12,
              pageIndex: 1,
              city: _this.currentCity,
              //城市
              cityLimit: 'true',
              panel: 'temp'//搜索结果的展示面板对元素id，不知道为什么一定要有该参数，最终获取的结果才更完整，参数更多跟完整，
              //所以我在页面随便写了一个<div id="temp" style="display:none"></div>
            });
            //关键字查询
            placeSearch.search(txt, function(status, result) {
              if (status == 'complete' && result.info == 'OK') {
                //这里可以console.log(result)，查看所有返回的参数，遍历展示这些基本的，我就不赘述
                _this.searchData = result.poiList.pois
              }
            })
          })
          setHeightKeyWord('nearby',txt,'#ec6045',false)
        },
        selectLocation(loc) {
          this.setLocation(loc)
          this.$router.push('/pay')
        },
        gotoAddNewAdr () {
          this.$router.push('/location/addNewLocation')
        },
        tobarHandler () {
          let path = this.$route.path
          if ((path.indexOf('selectLocation') == -1)&&(path.indexOf('addNewLocation') > -1)) {
            this.title = '新增收货地址'
            this.flag = false
          } else if ((path.indexOf('selectLocation') > -1)&&(path.indexOf('addNewLocation') > -1)){
            this.title = '选择收货地址'
            this.flag = false
          } else{
            this.title = '选择收货地址'
            this.flag = true
          }
        },
        ...mapMutations({
          setLocation: 'SET_LOCATION'
        })
      },
      computed: {
        ...mapGetters([
          'historyLocation'
        ])
      },
      watch: {
        '$route': 'tobarHandler'
      }
    }
</script>

<style scoped lang="scss">
  @import "../../common/sass/mixin";
  .location{
    height: 100vh;
    width: 100%;
    padding-top: 90px;
    background-color: $bc;
    position: relative;
    display: flex;
    flex-direction: column;
    .searchBox{
      @include font-dpr(28px);
      color: $fbc;
      display: flex;
      align-items: center;
      background-color: #ffffff;
      padding: 0 20px 0 34px;
      line-height: 80px;
      .currentLocation{
        &:after{
          content: "";
          display: inline-block;
          width: 20px;
          height: 20px;
          background: url("../../../static/img/downArrow.png") no-repeat center center;
          background-size: 100% 100%;
          margin-left: 12px;
        }
      }
      .inputBox{
        flex: 1;
        margin: 0 12px;
        input{
          @include font-dpr(24px);
          width: 100%;
          padding-left: 55px;
          background-image: url("../../../static/img/search.png");
          background-repeat: no-repeat;
          background-position: center left 14px;
          background-size: 32px 32px;
          outline: none;
          background-color: #ebebeb;
          border: none;
          border-radius: 5px;
          line-height: 54px;
        }
      }
      .searchBtn{}
    }
    .divider{
      color: $priceCor;
      @include font-dpr(28px);
      line-height: 80px;
      vertical-align: middle;
      display: flex;
      align-items: center;
      padding: 0 18px;
      img{
        height: 35px;
        width: 35px;
        margin-right: 20px;
      }
    }
    .addAddress{
      color: #ffffff;
    }
    .location-scroll{
      flex: 1;
      overflow: hidden;
      .nearby{
        padding-left: 18px;
        background-color: #ffffff;
        overflow: hidden;
        .nearby-item{
          border-bottom: 1px solid $borderCor;
          font-size: 0;
          padding: 0 60px 0 50px;
          overflow: hidden;
          .name{
            margin-top: 20px;
            color: $fbc;
            @include font-dpr(28px);
          }
          .area{
            margin-top: 5px;
            color: $fgc;
            @include font-dpr(24px);
          }
          .left{
            flex: 1;
            .left-name{
              margin-top: 20px;
              color: $fbc;
              @include font-dpr(28px);
            }
            .left-area{
              margin-top: 5px;
              color: $fgc;
              @include font-dpr(24px);
            }
          }
          .right{
            text-align: center;
            .right-img{
              height: 32px;
              width: 32px;
            }
            .right-content{
              color: $priceCor;
              @include font-dpr(24px);
            }
          }
          &:last-child {
            border: none;
          }
        }
        .flex{
          display: flex;
          align-items: center;
        }
      }
    }
  }
  .addNewLocation-enter-active,.addNewLocation-leave-active{
    transition: all 0.3s ease;
  }
  .addNewLocation-enter,.addNewLocation-leave-to{
    transform: translate3d(100%, 0, 0);
  }
  .addNewLocation-enter-to,.addNewLocation-leave{
    transform: translate3d(0, 0, 0);
  }
</style>
